package com.liy.framework.common.orm.mybatis.interceptor;

import java.sql.Statement;
import java.util.Properties;

import com.liy.framework.common.vo.PageVO;
import org.apache.ibatis.executor.resultset.ResultSetHandler;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.reflection.DefaultReflectorFactory;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.ReflectorFactory;
import org.apache.ibatis.reflection.factory.DefaultObjectFactory;
import org.apache.ibatis.reflection.factory.ObjectFactory;
import org.apache.ibatis.reflection.wrapper.DefaultObjectWrapperFactory;
import org.apache.ibatis.reflection.wrapper.ObjectWrapperFactory;
import org.apache.ibatis.session.RowBounds;


@Intercepts({ @Signature(type = ResultSetHandler.class, method = "handleResultSets", args = { Statement.class }) })
public class PaginationResultSetHandlerInterceptor implements Interceptor {

    private static final ObjectFactory DEFAULT_OBJECT_FACTORY;
    private static final ObjectWrapperFactory DEFAULT_OBJECT_WRAPPER_FACTORY;
    private static final ReflectorFactory DEFAULT_REFLECTOR_FACTORY;


    @Override
    public Object intercept(final Invocation invocation) throws Throwable {
        final ResultSetHandler resultSetHandler = (ResultSetHandler)invocation.getTarget();
        final MetaObject metaStatementHandler = MetaObject.forObject(resultSetHandler, PaginationResultSetHandlerInterceptor.DEFAULT_OBJECT_FACTORY, PaginationResultSetHandlerInterceptor.DEFAULT_OBJECT_WRAPPER_FACTORY, PaginationResultSetHandlerInterceptor.DEFAULT_REFLECTOR_FACTORY);
        final RowBounds rowBounds = (RowBounds)metaStatementHandler.getValue("rowBounds");
        final Object result = invocation.proceed();
        if (rowBounds instanceof PageVO) {
            metaStatementHandler.setValue("rowBounds.results", result);
        }
        return result;
    }


    @Override
    public Object plugin(final Object target) {
        return Plugin.wrap(target, this);
    }


    @Override
    public void setProperties(final Properties properties) {}
    
    static {
        DEFAULT_OBJECT_FACTORY = new DefaultObjectFactory();
        DEFAULT_OBJECT_WRAPPER_FACTORY = new DefaultObjectWrapperFactory();
        DEFAULT_REFLECTOR_FACTORY = new DefaultReflectorFactory();
    }
}
